package com.sqlSession;

import com.config.BoundSql;
import com.pojo.Configuration;
import com.pojo.MappedStatement;
import com.database.utils.GenericTokenParser;
import com.database.utils.ParameterMapping;
import com.database.utils.ParameterMappingTokenHandler;
import com.database.utils.TokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IDEA by ChouFy on 2020/2/20.
 *
 * @author Zhoufy
 */
public class SimpleExecutor implements Executor {


    private PreparedStatement getPreparedStatement(Configuration configuration, MappedStatement mappedStatement, Object... arguments) throws Exception {
        // 1. 注册驱动 获取连接
        Connection connection = configuration.getDataSource().getConnection();

        // 2. 获取sql语句 ， 转换sql
        // select * from user_info where id = #{id} -> select * from user_info where id=?;
        String sql = mappedStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);

        //3. 获取预处理对象 preparedStatement
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSql());

        //4. 设置参数
        String paramterType = mappedStatement.getParamterType();
        Class<?> paramterClass = getClassType(paramterType);
        List<ParameterMapping> parameters = boundSql.getParameters();
        for (int i = 0; i < parameters.size(); i++) {
            ParameterMapping parameterMapping = parameters.get(i);
            String content = parameterMapping.getContent();

            Field declaredField = paramterClass.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object o = declaredField.get(arguments[0]);

            preparedStatement.setObject(i + 1, o);
        }
        return preparedStatement;
    }

    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... arguments) throws Exception {
        PreparedStatement preparedStatement = getPreparedStatement(configuration, mappedStatement, arguments);

        //5. 执行sql
        ResultSet resultSet = preparedStatement.executeQuery();


        List<Object> objects = new ArrayList<>();
        //6. 封装返回结果集
        String resultType = mappedStatement.getResultType();
        Class resultTypeClass = getClassType(resultType);
        while (resultSet.next()) {
            ResultSetMetaData metaData = resultSet.getMetaData();
            Object o = resultTypeClass.newInstance();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                // 字段名
                String columnName = metaData.getColumnName(i);
                // 字段的值
                Object value = resultSet.getObject(columnName);

                // 使用反射根据数据库表和实体的对应的关系完成封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o, value);

            }
            objects.add(o);
        }
        return (List<E>) objects;
    }


    @Override
    public int update(Configuration configuration, MappedStatement mappedStatement, Object... arguments) throws Exception {

        PreparedStatement preparedStatement = getPreparedStatement(configuration, mappedStatement, arguments);

        //5. 执行sql
        int res = preparedStatement.executeUpdate();

        return res;
    }


    /**
     * 获取类的全路径获取class对象
     *
     * @param paramterType
     * @return
     */
    private Class<?> getClassType(String paramterType) throws ClassNotFoundException {
        if (paramterType != null) {
            return Class.forName(paramterType);
        }
        return null;
    }

    /**
     * 完成#{} 解析工作 将 #{} 使用 ？进行替换  解析#{} 里面的值进行存储
     *
     * @param sql
     * @return
     */
    private BoundSql getBoundSql(String sql) {

        TokenHandler tokenhandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", tokenhandler);
        String parseSql = genericTokenParser.parse(sql);
        //  #{}解析出来的参数名称
        List<ParameterMapping> parameterMappings = ((ParameterMappingTokenHandler) tokenhandler).getParameterMappings();

        return new BoundSql(parseSql, parameterMappings);
    }
}
